package com.fanwh.healthycampus2.fragment;


import android.os.Bundle;

import androidx.appcompat.app.AlertDialog;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.DefaultItemAnimator;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import com.fanwh.healthycampus2.R;
import com.fanwh.healthycampus2.adapter.InformationAdapter;
import com.fanwh.healthycampus2.bean.HealthyInformation;
import com.fanwh.healthycampus2.bean.User;
import com.fanwh.healthycampus2.utils.DividerItemDecoration;

import java.util.ArrayList;
import java.util.List;

import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.BmobUser;
import cn.bmob.v3.datatype.BmobQueryResult;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.FindListener;
import cn.bmob.v3.listener.SQLQueryListener;

/**
 * A simple {@link Fragment} subclass.
 */
public class RecordFragment extends Fragment {

    private SwipeRefreshLayout swipeRefreshLayout;
    private RecyclerView recyclerView;

    private List<HealthyInformation> healthyInformationList = new ArrayList<>();


    public RecordFragment() {
        // Required empty public constructor
    }

    private Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what){
                case 0x101:
                    if (swipeRefreshLayout.isRefreshing()){
                        swipeRefreshLayout.setRefreshing(false);//设置不刷新
                    }
                    break;
            }
        }
    };


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View inflate =  inflater.inflate(R.layout.fragment_record, container, false);
        swipeRefreshLayout = inflate.findViewById(R.id.record_swipe);
        recyclerView = inflate.findViewById(R.id.recycler_view);

        LinearLayoutManager layoutManager= new LinearLayoutManager(getActivity());
        recyclerView.setLayoutManager(layoutManager);
        recyclerView.setItemAnimator(new DefaultItemAnimator());

        //设置RecyclerView的Item分割线
        recyclerView.addItemDecoration(new DividerItemDecoration(getActivity(), DividerItemDecoration.VERTICAL_LIST));
        InformationAdapter adapter = new InformationAdapter(healthyInformationList);
        recyclerView.setAdapter(adapter);

        swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                if (recyclerView.getChildCount()>0){
                    //recyclerView.removeAllViews();
                    //adapter.notifyDataSetChanged();
                    healthyInformationList.clear();
                    System.out.println("你有做一步吗");
                }
                new RecordDataThread().start();
            }
        });
        return inflate;
    }

    class RecordDataThread extends Thread{
        @Override
        public void run(){

            recordData();
            try {
                Thread.sleep(2000);
            }catch (InterruptedException e){
                e.printStackTrace();
            }
            handler.sendEmptyMessage(0x101);
        }

        private void recordData() {

            initData();
        }
    }

    private void initData() {
        User user = BmobUser.getCurrentUser(User.class);
        String username = (String) BmobUser.getObjectByKey("username");
        BmobQuery<HealthyInformation> query = new BmobQuery<HealthyInformation>();
        query.addWhereEqualTo("student",user);
        String sql = "SELECT * From HealthyInformation where studentID = '"+username+"'ORDER BY createdAt DESC LIMIT 50";
        query.doSQLQuery(sql, new SQLQueryListener<HealthyInformation>() {
            @Override
            public void done(BmobQueryResult<HealthyInformation> bmobQueryResult, BmobException e) {
                if(e == null){
                    List<HealthyInformation> list = bmobQueryResult.getResults();
                    Toast.makeText(getActivity(),"查询成功：共"+list.size()+"条数据",Toast.LENGTH_SHORT).show();
                    String str = " ";
                    for(HealthyInformation healthyInformation : list){
                        HealthyInformation test = new HealthyInformation();
                        test.setName(healthyInformation.getName());
                        test.setStudentID(healthyInformation.getStudentID());
                        test.setSchool(healthyInformation.getSchool());
                        test.setTemperature(healthyInformation.getTemperature());
                        test.setDate(healthyInformation.getCreatedAt());
                        healthyInformationList.add(test);

                    }
                }else {
                    System.out.println(e.getErrorCode());
                }
            }
        });
        /*
        System.out.println(user);

        query.order("-createdAt");

        query.findObjects(new FindListener<HealthyInformation>(){
            @Override
            public void done(List<HealthyInformation> list, BmobException e){
                if(e == null){
                    Toast.makeText(getActivity(),"查询成功：共"+list.size()+"条数据",Toast.LENGTH_LONG).show();

                    for(HealthyInformation healthyInformation : list){
                        HealthyInformation test = new HealthyInformation();
                        test.setName(healthyInformation.getName());
                        test.setStudentID(healthyInformation.getStudentID());
                        test.setSchool(healthyInformation.getSchool());
                        test.setTemperature(healthyInformation.getTemperature());
                        test.setDate(healthyInformation.getCreatedAt());
                        healthyInformationList.add(test);
                    }
                }else {
                    System.out.println(e.getErrorCode());
                }
            }
        });

         */
    }

}
